from collections import deque
from typing import List, Dict, Any, Sequence


def distinct(objs: Sequence[Any]) -> Sequence[Any]:
    return list({id(obj): obj for obj in objs}.values())

async def flatten_tree(
    tree_list: List[Dict[str, Any]], is_del_children: bool = False
) -> List[Dict[str, Any]]:
    flat_list = []
    for item in tree_list:
        new_obj = {**item}
        # 如果新对象里面还存在 children 属性，则删除这个属性
        if is_del_children and "children" in new_obj:
            del new_obj["children"]

        # 将新对象添加到列表
        flat_list.append(new_obj)

        # 如果存在自身循环引用的 children 属性，则递归处理
        if "children" in item:
            flat_list.extend(await flatten_tree(item["children"]))

    return flat_list


def tree_to_2d_list_dfs(node, path=None, result=None):
    """深度优先遍历（DFS）"""
    if result is None:
        result = []
    if path is None:
        path = []

    current_path = path + [node["name"]]
    result.append(current_path)

    for child in node.get("children", []):
        tree_to_2d_list_dfs(child, current_path, result)

    return result


def tree_to_2d_list_bfs(root):
    """广度优先遍历（BFS）"""
    if not root:
        return []

    result = []
    queue = deque([root])

    while queue:
        level_size = len(queue)
        current_level = []

        for _ in range(level_size):
            node = queue.popleft()
            current_level.append(node["name"])  # 假设每个节点有'name'属性

            for child in node.get("children", []):
                queue.append(child)

        result.append(current_level)

    return result
